package com.wlb365.admin.modules.schema.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlb365.admin.common.dto.R;
import com.wlb365.admin.common.support.controller.BaseController;
import com.wlb365.admin.modules.monitor.service.MonitorInfoErrorService;
import com.wlb365.admin.modules.monitor.service.MonitorInfoService;
import com.wlb365.admin.modules.schema.dto.SchemaDTO;
import com.wlb365.admin.modules.schema.entity.Node;
import com.wlb365.admin.modules.schema.util.JsonSchemaUtil;
import com.wlb365.admin.modules.sys.service.IUserService;
import com.wlb365.feign.api.dto.TemplateAddDTO;
import com.wlb365.feign.api.dto.TemplateDTO;
import com.wlb365.feign.api.dto.TemplateQueryDTO;
import com.wlb365.feign.api.dto.TemplateUpdateDTO;
import com.wlb365.feign.api.result.RTemplateData;
import com.wlb365.feign.api.service.ITemplateService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 模板 前端控制器.
 * </p>
 *
 * @author
 * @since 2021-01-27 13:18:15
 */
@RestController
@RequestMapping("template/info")
public class TemplateController extends BaseController {

    @Autowired
    private MonitorInfoService infoService;
    @Autowired
    private IUserService userService;
    @Autowired
    private MonitorInfoErrorService monitorInfoErrorService;

    @Autowired
    private ITemplateService templateService;

    @RequiresPermissions("template:info:index")
    @GetMapping("index")
    public ModelAndView index() {
        return new ModelAndView("template/template");
    }

    @GetMapping(value = "list/data")
    public R listData(TemplateDTO dto) {
        Page<RTemplateData> page = templateService.page(dto);
        return R.ok(page);
    }

    @GetMapping(value = "edit")
    public ModelAndView edit(@RequestParam(required = false, value = "id") String id, @RequestParam(required = false, value = "action") String action) {
        ModelAndView mv = new ModelAndView("template/template_edit");
        RTemplateData rTemplateData = new RTemplateData();
        if (id != null) {
            TemplateQueryDTO dto = new TemplateQueryDTO();
            dto.setId(id);
            rTemplateData = templateService.one(dto);
        }
        mv.addObject("editInfo", rTemplateData);
        mv.addObject("action", action);
        return mv;
    }

    @GetMapping(value = "preview")
    public ModelAndView preview(String id) {
        ModelAndView mv = new ModelAndView("template/template_preview");
        RTemplateData rTemplateData = new RTemplateData();
        if (id != null) {
            TemplateQueryDTO dto = new TemplateQueryDTO();
            dto.setId(id);
            rTemplateData = templateService.one(dto);
        }
        mv.addObject("editInfo", rTemplateData);
        return mv;
    }


    //模拟jsonschema文件
    String schema = "{\"$schema\":\"https://json-schema.org/draft/2019-09/schema\",\"description\":\"企业信息数据格式\",\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"企业ID\",\"minLength\":3,\"maxLength\":32},\"type\":{\"type\":\"string\",\"enum\":[\"enterprise\"],\"description\":\"类型\"},\"name\":{\"type\":\"string\",\"description\":\"企业名称\"},\"status\":{\"type\":\"string\",\"enum\":[\"0\",\"1\",\"2\",\"3\"],\"description\":\"企业状态（0-在营、1-开业、2-注册、3-注销）\"},\"registrationNo\":{\"type\":\"string\",\"maxLength\":50,\"description\":\"工商注册号\"},\"registrationAuthority\":{\"type\":\"string\",\"description\":\"登记机关\"},\"registrationDate\":{\"type\":\"string\",\"description\":\"注册日期\"},\"englishNmae\":{\"type\":\"string\",\"description\":\"英文名称\"},\"industry\":{\"type\":\"string\",\"description\":\"所属行业\"},\"businessScope\":{\"type\":\"string\",\"description\":\"经营范围\"},\"businessLicenseUrl\":{\"type\":\"string\",\"description\":\"营业执照url\"},\"socialCode\":{\"type\":\"string\",\"description\":\"社会信用代码\"},\"location\":{\"type\":\"string\",\"description\":\"所在地区\"},\"address\":{\"type\":\"string\",\"description\":\"经营地址\"},\"enterpriseScale\":{\"type\":\"string\",\"description\":\"企业规模（人数范围）\"},\"beforeName\":{\"type\":\"string\",\"description\":\"曾用名\"},\"contact\":{\"type\":\"string\",\"description\":\"联系人\"},\"contactNumber\":{\"type\":\"string\",\"description\":\"联系电话\"},\"contactNumber\":{\"type\":\"string\",\"description\":\"联系电话\"},\"zipCode\":{\"type\":\"string\",\"description\":\"邮编\"},\"fax\":{\"type\":\"string\",\"description\":\"传真\"},\"imageUrl\":{\"type\":\"object\",\"stype\":\"file\",\"description\":\"文件信息\",\"properties\":{\"url\":{\"type\":\"string\",\"description\":\"文件url\"},\"hash\":{\"type\":\"string\",\"description\":\"文件hash\"}}},\"legalPerson\":{\"type\":\"object\",\"description\":\"法人信息\",\"properties\":{\"name\":{\"type\":\"string\",\"description\":\"姓名\"},\"tel\":{\"type\":\"string\",\"description\":\"电话\"},\"age\":{\"type\":\"integer\",\"description\":\"年龄\",\"minimum\":18},\"idType\":{\"type\":\"string\",\"enum\":[\"0\",\"1\"],\"description\":\"证件类型（0-身份证）\"},\"idNumber\":{\"type\":\"string\",\"description\":\"证件号\"},\"idImageUrl\":{\"type\":\"string\",\"description\":\"证件图片URL\"},\"relatedCompanies\":{\"type\":\"string\",\"description\":\"关联公司\"}},\"required\":[\"name\",\"tel\",\"age\",\"idType\",\"idNumber\",\"idImageUrl\"]}},\"required\":[\"id\",\"name\",\"type\",\"legalPerson\"]}";

    @GetMapping(value = "getSchema")
    public R getSchema(String id) {
        R r = null;
        List<LinkedHashMap<String, Object>> data = new ArrayList<>();
        String tempstr = "";
        if (StrUtil.isNotEmpty(id)) {
            TemplateQueryDTO dto = new TemplateQueryDTO();
            dto.setId(id);
            RTemplateData templateData = templateService.one(dto);
            tempstr = templateData.getTemplateData();
            JsonSchemaUtil.jsonSchemaToTree(data, tempstr);
            r = new R(0, "成功", data);
            return r;
        }
        r = new R(0, "失败", null);
        return r;
    }

    @RequiresPermissions("schema:info:edit")
    @Transactional
    @PostMapping(value = "edit")
    public R edit(final SchemaDTO schema) {
        //TODO 将data转换为json schema数据
        //1. data数组转换为json schema
        if (StrUtil.isEmpty(schema.getTemplateData())) {
            return R.fail("模板数据不能为空！");
        }
//        List<Node> schemaEntities = JSON.parseArray(data, Node.class);
//
//        Map<String, Node> nodeMap = schemaEntities.stream().collect(Collectors.toMap(Node::getId, node -> node));
//


        //2. 判断系统模板 or 用户模板
        // 2.1 系统模板，新增一条模板记录
        // 2.1 用户模板，修改当前用户模板
        //3. 保存模板信息
        // System.out.println(schema.getData());

        if (StrUtil.isNotEmpty(schema.getId())) {
            TemplateUpdateDTO updateDTO = new TemplateUpdateDTO();
            BeanUtil.copyProperties(schema, updateDTO);
            templateService.update(updateDTO);
        } else {
            TemplateAddDTO dto = new TemplateAddDTO();
            BeanUtil.copyProperties(schema, dto);
            templateService.add(dto);
        }
        return R.ok();
    }


}

